import React, { Component, Fragment } from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';
import router from 'umi/router';

import _ from 'lodash';

import { Form } from '@ant-design/compatible';
import PageHeader from '@/components/PageHeader';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import {
  Card,
  Row,
  Col,
  Select,
  Descriptions,
  Button,
} from 'antd';

import '@ant-design/compatible/assets/index.css';

const { Option } = Select;
const { Item } = Descriptions;

const region_list_init = [
  {
    index: 1, // 序号
    type: 1, // 分区类型
    id: 0, // 分区id
    numId: 0, // 当前此条记录的id
    title: '异形-未识别', // 名称
    number: 100, // 分拣口编号(格口编号)
    sort: 1, // 与number数值相同，用于排序判断
  },
  {
    index: 2,
    type: 2,
    id: 0,
    numId: 0,
    title: '异形-已识别',
    number: 100,
    sort: 1,
  },
];

interface SortingInfoProps extends FormComponentProps {
  dispatch: Dispatch;
  sortingInfo: any;
  regionInfo: any;
  location: { query: any };
}

interface SortingInfoState {
  region_list: any;
  is_add: boolean;
}

@connect(({
  logisticsCenterSorting: { sortingInfo, regionInfo },
}: any) => ({
  sortingInfo,
  regionInfo,
}))

class SortingInfoElem extends Component<SortingInfoProps, SortingInfoState> {
  state: SortingInfoState = {
    region_list: region_list_init,
    is_add: true, // 是否为添加
  };

  static getDerivedStateFromProps(nextProps: SortingInfoProps, perState: SortingInfoState) {
    const { sortingInfo, regionInfo } = nextProps;

    if (sortingInfo?.list?.length > 0 || regionInfo.length > 0) {
      const region = regionInfo.map((item: any, index: number) => ({
        index: index + 3,
        type: 3,
        id: item.id,
        numId: 0,
        title: item.name,
        sort: 1,
        // number: 1,
      }));
      const new_info = _.cloneDeep(region_list_init);
      const new_region = [...new_info, ...region];

      new_region.map((item: any) => sortingInfo.list.filter((sort: any) => {
        if ((sort.regionType === 1 && item.type === 1)
          || (sort.regionType === 2 && item.type === 2)
          || (sort.regionType === 3 && item.type === 3 && item.id === sort.regionId)
        ) {
          item.numId = sort.id;
          item.number = Number(sort.sortNumber);
          item.sort = Number(sort.sortNumber);
        }
        return false;
      }));

      return {
        region_list: new_region,
        is_add: Boolean(!sortingInfo.list),
      };
    }
    return null;
  }

  componentDidMount() {
    const { location: { query: { logisId } } } = this.props;
    if (logisId) this.fetchDataInfo(logisId);
  }

  componentDidUpdate(prevProps: any) {
    const { location: { query: { logisId } } } = this.props;
    if (logisId && logisId !== prevProps.location.query.logisId) {
      this.fetchDataInfo(logisId);
    }
  }

  componentWillUnmount() {
    this.fetchAction('clear');
  }

  fetchDataInfo = (logisId: number) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'logisticsCenterSorting/fetch',
      payload: { logisId },
    });

    dispatch({
      type: 'logisticsCenterSorting/fetchRegion',
      payload: { logisId },
    });
  };

  handleSubmit = () => {
    const { form: { validateFieldsAndScroll } } = this.props;
    validateFieldsAndScroll((errors, values) => {
      if (errors) return;

      const { region_list, is_add } = this.state;
      const list = [...region_list];
      const sortStr = values.number.map((num: number, index: number) => (is_add
        ? `${list[index].type}-${list[index].id}-${num}`
        : `${list[index].numId}-${list[index].type}-${list[index].id}-${num}`));

      const { location: { query } } = this.props;
      const params = {
        type: is_add,
        ...query,
        sortStr: sortStr.join(','),
      };
      this.fetchAction('saveOrUpdate', params);
    });
  };

  fetchAction = (typeName: string, payload: any = {}) => {
    const { dispatch } = this.props;
    const type = typeName.indexOf('common') >= 0
      ? typeName : `logisticsCenterSorting/${typeName}`;
    dispatch({ type, payload });
  };

  render() {
    const { region_list } = this.state;
    const {
      form: { getFieldDecorator },
      location: { query },
    } = this.props;

    const Schematic = `../../../../../${region_list.length >= 8 ? 8 : region_list.length}.png`;

    return (
      <Fragment>
        <PageHeader />

        <Form hideRequiredMark className="tableListForm">
          <Card bordered={false}>
            <Row gutter={{ md: 8, xl: 24, lg: 48 }}>
              <Col md={16} sm={24}>
                <Row>
                  <Col md={16} sm={24}>
                    <Form.Item label="物流中心(小区)名称">
                      <div>{query.name}</div>
                    </Form.Item>
                  </Col>
                </Row>
                {
                  region_list.map((item: any, index: number) => (
                    <Row key={item.index} className="marginB20">
                      <Col md={12} sm={24}>
                        <Form.Item label={item.title} colon={false} className="marginB0Import">
                          {getFieldDecorator(`number[${index}]`, {
                            initialValue: item.number || 100,
                            rules: [{ required: true, message: `请设置${item.title}分拣口` }],
                          })(
                            <Select placeholder="请选择" style={{ width: '96%' }}>
                              {
                                region_list.map((subItem: any, num: number) => (
                                  // 张倩  bug修复  2020-9-8
                                  <Option key={subItem.index} value={num + 1}>
                                    分拣口{num + 1}
                                  </Option>
                                ))
                              }
                              <Option value={100}>无分拣口</Option>
                            </Select>,
                          )}
                        </Form.Item>
                      </Col>
                      {item.type === 1 && (
                        <Col
                          md={10}
                          sm={24}
                          style={{ color: 'red' }}
                        >
                          *运单号和手机号未能识别对的包裹
                        </Col>
                      )}
                      {item.type === 2 && (
                        <Col
                          md={10}
                          sm={24}
                          style={{ color: 'red' }}
                        >
                          *已识别运单号和手机号但分区未知的包裹
                        </Col>
                      )}
                    </Row>
                  ))
                }
              </Col>
              <Col md={8} sm={24}>
                <img
                  src={Schematic}
                  alt=""
                  style={{ width: '100%' }}
                />
              </Col>
            </Row>
            <Descriptions title="说明" column={1}>
              <Item> 1、仅支持状态为“有效”的物流中心或小区的分区配置分拣机分拣口。</Item>
              <Item>2、支持多个分区配置至同一分拣口，但异形分拣口不能与有效分区的分拣口相同。</Item>
              <Item>3、新增分区后，需重新给新区配置分拣口才生效。</Item>
            </Descriptions>
          </Card>

          <Card bordered={false} className="marginB24">
            <Button
              type="primary"
              onClick={this.handleSubmit}
            >
              保存
            </Button>
            <Button
              ghost
              type="primary"
              className="marginL16"
              onClick={router.goBack}
            >
              取消
            </Button>
          </Card>
        </Form>
      </Fragment>
    );
  }
}

export default Form.create<SortingInfoProps>()(SortingInfoElem);
